<template>
  <div class="login-container">
    <div class="login-div">
      <div class="login-title">
        <h1>招&nbsp;商&nbsp;线&nbsp;索&nbsp;管&nbsp;理&nbsp;平&nbsp;台</h1>
      </div>
      <el-form :model="form" label-width="auto" style="max-width: 600px">
        <el-form-item label="帐号">
          <el-input v-model="form.username"/>
        </el-form-item>
        <el-form-item label="密码">
          <el-input type="password" v-model="form.password" show-password/>
        </el-form-item>
        <el-form-item label="验证码">
          <el-input class="verification-input" v-model="form.captchaCode"/>
          <img style="margin-left: 20px" @click="resetCaptcha" :src="captchaUrl" width="120px" height="40px"
               alt="无法获取验证码">
        </el-form-item>
        <el-form-item>
          <el-button class="login-btn" type="primary" @click="onSubmit">登录</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>

</template>

<script setup>
import {onMounted, reactive, ref} from 'vue'
import {loginApi, getCaptchaApi} from "@/assets/api/login";
import {useCookies} from "vue3-cookies";
import {ElMessage} from "element-plus";
import router from "@/assets/router";

// 表单参数
const form = reactive({
  username: '',
  password: '',
  captchaKey: '',
  captchaCode: '',
  loginFlag: '1'
})

// 验证码地址
const captchaUrl = ref('');

// 登录
const onSubmit = () => {
  loginApi(form).then(res => {
    if (res.data.code === 200) {
      ElMessage("登录成功");
      useCookies().cookies.set("token", res.data.data.token);
      useCookies().cookies.set("name", res.data.data.name);
      router.push("/index");
    } else if (res.data.code === 403) {
      ElMessage(res.data.msg);
    } else {
      ElMessage(res.data.data);
    }
  })
}

// 刷新验证码
const resetCaptcha = () => {
  getCaptchaApi().then(res => {
    const binary = new Uint8Array(res.data);
    const base64 = btoa(String.fromCharCode.apply(null, binary));
    captchaUrl.value = 'data:image/jpeg;base64,' + base64;
    form.captchaKey = res.headers.get("captchaKey");
  })
}

onMounted(() => {
  resetCaptcha();
});
</script>

<style scoped>
.login-container {
  position: absolute;
  width: 100%;
  height: 100%;
  background-image: url("@/assets/img/login.png");
  background-size: cover;
}

.login-div {
  background-color: rgba(55, 112, 255, 0.2);
  position: absolute;
  top: 27%;
  left: 37%;
  width: 350px;
  height: 340px;
  padding: 20px;
  border: 1px solid #0070ed;
  border-radius: 10px;
}

.login-title {
  text-align: center;
  color: aliceblue;
  padding-bottom: 20px;
}


:deep(.el-form-item__label) {
  color: aliceblue;
}

.verification-input {
  width: 50%;
  display: inline-block;
}

.login-btn {
  margin-top: 15px;
  height: 45px;
  width: 100%;
}
</style>